#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
using namespace std;
// 创建四个进程模拟抢票：
int ticket = 1000;

void *route(void *arg)
{
    pthread_mutex_t*lk= static_cast< pthread_mutex_t*>(arg);
    while (1)
    {   //保护临界区
        pthread_mutex_lock(lk);
        if (ticket > 0) // 1. 判断
        {
            usleep(1000);                               // 模拟抢票花的时间
            printf("pthread sells ticket:%d\n",  ticket); // 2. 抢到了票
            ticket--;                                   // 3. 票数--
            pthread_mutex_unlock(lk);
        }
        else
        {
            pthread_mutex_unlock(lk);
            //这里还需要解锁否则到最后抢完票线程加锁后有其他线程不能被join进而阻塞住

            break;
        }
    }
    return nullptr;
}
int main()
{ 
    pthread_mutex_t lock;
    pthread_mutex_init(&lock,nullptr);
    pthread_t t1, t2, t3, t4;

    pthread_create(&t1, NULL, route, &lock);
    pthread_create(&t2, NULL, route, &lock);
    pthread_create(&t3, NULL, route, &lock);
    pthread_create(&t4, NULL, route, &lock);
    pthread_mutex_destroy(&lock);
    
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);
}